package per.wsj.okhttp.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.*
import per.wsj.httplib.ok.LoadState
import per.wsj.httplib.ok.exception.ExceptionUtils

/**
 * ViewModel 基类
 * @author wangsj
 */
abstract class BaseViewModel : ViewModel() {
    // 加载状态
    val loadState = MutableLiveData<LoadState>()

    fun launch(block: suspend CoroutineScope.() -> Unit) {
        viewModelScope.launch {
            try {
                loadState.value = LoadState.Start
                withContext(Dispatchers.IO) {
                    block.invoke(this)
                }
            } catch (throwable: Throwable) {
                // handle error
                val error = ExceptionUtils.parseException(throwable)
                loadState.value = LoadState.Error(error)
            } finally {
                loadState.value = LoadState.Finish
            }
        }
    }
}